package com.example.anwserai.demos.web.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
 * @author cao
 * @title kkfilecontroller
 * @date 2025/3/15 16:37
 * @description TODO
 */
@RestController
public class kkfilecontroller {





        @PostMapping("/upload")
        public Map uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
            Map map = new HashMap();
            // 1. 生成唯一文件名（避免冲突）
                String originalFilename = file.getOriginalFilename();
                String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
                String uniqueFileName = UUID.randomUUID() + fileExtension;

                // 2. 保存文件到本地
                Path uploadPath = Paths.get("uploadDir");
                if (!Files.exists(uploadPath)) {
                    Files.createDirectories(uploadPath);
                }
                Path filePath = uploadPath.resolve(uniqueFileName);
                Files.copy(file.getInputStream(), filePath);

                // 3. 生成可访问的 URL（假设服务地址为 http://localhost:8080）
                String fileUrl = "http://localhost:8080/files/" + uniqueFileName;

                // 4. 返回结果（包含文件 URL 和解析结果）
            map.put("fileUrl",fileUrl);
                return map;


        }
}
